const doRequest = require("./signer.js");
const sharp = require("sharp");
const request = require("request");

// 获取人脸坐标
const getFaceBox = async (base64) => {
  const params = {
    query: {
      Action: "BodyDetection",
      Version: "2022-08-31",
    },
    contentType: "application/json",
    data: {
      req_key: "face_body_detection",
      binary_data_base64: [base64],
    },
  };

  const { data } = await doRequest(params);
  const result = data.data.result;
  const val = result[0].filter((e) => e.eng_name === "face")[0];
  if (parseFloat(val.score) > 0.5) {
    return request(200, val);
  } else {
    return request(400, "请提供清晰的图片");
  }
};

// 扣除背景
const handleBackground = async (base64) => {
  const params = {
    query: {
      Action: "SaliencySeg",
      Version: "2022-08-31",
    },
    contentType: "application/json",
    data: {
      req_key: "saliency_seg",
      refine_mask: 1,
      binary_data_base64: [base64],
    },
  };
  const { data } = await doRequest(params);
  if (data.code === 10000) {
    return request(200, data.data.binary_data_base64[0]);
  } else {
    return request(400, "图片中没有找到人体！");
  }
};

// 根据人脸坐标、返回裁剪后的图片
const createIDPhotoBase64 = async (base64Str, faceBox, outputSize) => {
//   const base64Data = base64Str.replace(/^data:image\/\w+;base64,/, "");
  const imageBuffer = Buffer.from(base64Str, "base64");

  const image = sharp(imageBuffer);
  const metadata = await image.metadata();
  const imgWidth = metadata.width;
  const imgHeight = metadata.height;

  // 将 faceBox 的字符串转为数值
  const x1 = parseFloat(faceBox.x1);
  const x2 = parseFloat(faceBox.x2);
  const y1 = parseFloat(faceBox.y1);
  const y2 = parseFloat(faceBox.y2);

  // 人脸中心点
  const faceCenterX = (x1 + x2) / 2;
  const faceCenterY = (y1 + y2) / 2;

  // 根据目标比例计算裁剪区域
  const aspectRatio = outputSize.width / outputSize.height;
  let cropHeight = (y2 - y1) * 2.5; // 人脸高度的2倍
  let cropWidth = cropHeight * aspectRatio;

  // 边界处理
  if (cropWidth > imgWidth) cropWidth = imgWidth;
  if (cropHeight > imgHeight) cropHeight = imgHeight;

  const left = Math.max(
    0,
    Math.min(imgWidth - cropWidth, faceCenterX - cropWidth / 2)
  );
  const top = Math.max(
    0,
    Math.min(imgHeight - cropHeight, faceCenterY - cropHeight / 2)
  );

  // 裁剪 + 缩放
  const outputBuffer = await sharp(imageBuffer)
    .extend({ top: 40, background: { r: 0, g: 0, b: 0, alpha: 0 } })
    .extract({
      left: Math.round(left),
      top: Math.round(top),
      width: Math.round(cropWidth),
      height: Math.round(cropHeight),
    })
    .resize(outputSize.width, outputSize.height)
    .png()
    .toBuffer();

  // 按照要求，从底部裁剪40像素
  const outputBufferCropped = await sharp(outputBuffer)
    .extract({
      left: 0,
      top: 0,
      width: outputSize.width,
      height: outputSize.height,
    })
    .png()
    .toBuffer();

  const base64Cropped = outputBufferCropped.toString("base64");
  return base64Cropped;
};

const setBackground = async (base64Img, background) => {
  try {
    // 将base64转换为buffer
    // const base64Data = base64Img.replace(/^data:image\/\w+;base64,/, "");
    const inputBuffer = Buffer.from(base64Img, "base64");

    // 获取图片信息
    const image = sharp(inputBuffer);
    const metadata = await image.metadata();

    // 创建背景色图层
    const bgLayer = await sharp({
      create: {
        width: metadata.width,
        height: metadata.height,
        channels: 4,
        background: background
      }
    }).png().toBuffer();

    // 合成图片
    const composited = await sharp(bgLayer)
      .composite([{ input: inputBuffer }])
      .png()
      .toBuffer();

    // 转base64
    return composited.toString('base64');
  } catch (err) {
    console.error('设置背景色失败:', err);
    return null;
  }
}

module.exports = {
  getFaceBox,
  createIDPhotoBase64,
  handleBackground,
  setBackground
};
